package com.ibiaoke.common.spring;

import com.ibiaoke.common.exception.ServiceException;
import com.ibiaoke.common.response.Res;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by jackjiang on 17/4/17.
 */
@Aspect
public class ExceptionAspect {
    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(ExceptionAspect.class);

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void exceptionAspect() {}

    @Around(value = "exceptionAspect()")
    public Object runAround(JoinPoint joinPoint) {
        //        操作记录日志
        Signature signature = joinPoint.getSignature();
        //Rest Class Name
        String restClassName = joinPoint.getTarget().getClass().getName();
        //请求方法名称
        String methodName = signature.getName();
        //记录当前时间
        Long curTime = System.currentTimeMillis();
        String result="成功";
        try {
            return ((ProceedingJoinPoint) joinPoint).proceed();
        } catch (Throwable throwable) {
            if(throwable instanceof ServiceException){
                logger.info(throwable.getLocalizedMessage(), throwable);
            }else{
                logger.error(throwable.getLocalizedMessage(), throwable);
            }
            result="失败";
            return this.createThrowableMessage(throwable);
        } finally {
            logger.info("请求{}.{}{},响应时间:{}ms", restClassName, methodName,result, System.currentTimeMillis() - curTime);
        }
    }

    /**
     * 异常信息处理
     *
     * @param ex  Throwable
     */
    private Res createThrowableMessage(Throwable ex) {
        String message = "系统异常,请联系管理员";
        if (ex instanceof ServiceException) {
            if(ex.getCause()!=null && ex.getCause() instanceof  ServiceException){
                ex=ex.getCause();
            }
            message = ex.getLocalizedMessage();
        }
        return Res.createErrorRes(message);
    }

}
